//
//  NetworkServiceManager.m
//  laziz_Consumer
//
//  Created by XMac on 16/11/9.
//  Copyright © 2016年 XBN. All rights reserved.
//

#define IS_LEGAl(str) ((str && ![str isEqualToString:@""]))
#define REQUEST_CREATE(urlStr) [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];



#import "NetworkServiceManager.h"

@implementation NetworkServiceManager


+(instancetype)manager{
    
    static NetworkServiceManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[NetworkServiceManager alloc]init];
    });
    
    return manager;
}


+(AFURLSessionManager *)urlSessionManager{
    static AFURLSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    });
    
    return manager;
}

+(AFHTTPSessionManager *)httpSessionManager{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:APIBaseURL]];
        AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
        manager.requestSerializer = serializer;
    });
    
    return manager;
}


+(AFHTTPSessionManager *)httpUpLoadSessionManager{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:APIBaseURL]];
        AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
        manager.requestSerializer = serializer;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    });
    
    return manager;
}


/**
 下载文件

 @param urlStr 下载地址
 @param progressHandler 进度block
 @param completionHandler 下载完成block
 @return task对象
 */
-(NSURLSessionDownloadTask *)executeDownloadTask:(NSString *)urlStr progress:(ProgressHandler)progressHandler completion:(DownloadCompletionHandler)completionHandler{
    NSAssert(IS_LEGAl(urlStr), @"urlStr 不能为空");
    
    AFURLSessionManager *manager = [NetworkServiceManager urlSessionManager];
    NSURLRequest *request = REQUEST_CREATE(urlStr);
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
        
        if (progressHandler) {
            ///同步
            dispatch_sync(dispatch_get_main_queue(), ^{
                progressHandler(downloadProgress);
            });
        }
    }destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        ///存到的地址
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        ///处理完成
        if (completionHandler) {
            completionHandler(response,filePath,error);
        }
    }];
    [downloadTask resume];
    
    return downloadTask;
}



/**
 上传文件

 @param urlStr 上传地址
 @param xfilePath 上传文件地址
 @param progressHandler 进度block
 @param completionHandler 上传完成block
 @return task对象
 */
-(NSURLSessionUploadTask *)executeUploadTask:(NSString *)urlStr filePath:(NSString *)xfilePath progress:(ProgressHandler)progressHandler completion:(UploadCompletionHandler)completionHandler{
    
    NSAssert(IS_LEGAl(urlStr), @"urlStr 不能为空");
    NSAssert(IS_LEGAl(xfilePath), @"xfilePath 不能为空");
    
    AFURLSessionManager *manager = [NetworkServiceManager urlSessionManager];
    
    NSURLRequest *request = REQUEST_CREATE(urlStr);
    
    NSURL *filePath = [NSURL fileURLWithPath:xfilePath];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress *uploadProgress){
        if (progressHandler) {
            ///同步
            dispatch_sync(dispatch_get_main_queue(), ^{
                progressHandler(uploadProgress);
            });
        }
    }completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        
        ///处理完成
        if (completionHandler) {
            completionHandler(response,responseObject,error);
        }
    }];
    [uploadTask resume];

    return uploadTask;
}


/**
 get请求的便利方法
 */
-(NSURLSessionDataTask *)executGetTask:(NSString *)urlStr parameters:(id)parameter success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success fail:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure{
    
    return [self executGetTask:urlStr parameters:parameter progress:nil success:success fail:failure];
}


/**
 get请求

 @param urlStr 请求地址
 @param parameter 参数
 @param progressHandler 进度
 @param success 成功block
 @param failure 失败block
 @return task对象
 */
-(NSURLSessionDataTask *)executGetTask:(NSString *)urlStr parameters:(id)parameter progress:(ProgressHandler)progressHandler success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success fail:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
    
    IS_LEGAl(urlStr);
    
    AFHTTPSessionManager *manager = [NetworkServiceManager httpSessionManager];
    
    NSURLSessionDataTask *dataTask = [manager GET:urlStr parameters:parameter progress:^(NSProgress * _Nonnull progress) {
        if (progressHandler) {
            ///同步
            dispatch_sync(dispatch_get_main_queue(), ^{
                progressHandler(progress);
            });
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(task,responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(task,error);
        }
    }];
    
    return dataTask;
}



/**
 post请求便利方法
 */
-(NSURLSessionDataTask *)executePostTask:(NSString *)urlStr parameters:(id)parameter success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success fail:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure{
    
    return [self executePostTask:urlStr parameters:parameter progress:nil success:success fail:failure];
}

/**
 post请求

 @param urlStr 请求地址
 @param parameter 参数
 @param progressHandler 进度
 @param success 成功block
 @param failure 失败block
 @return task对象
 */
-(NSURLSessionDataTask *)executePostTask:(NSString *)urlStr parameters:(id)parameter progress:(ProgressHandler)progressHandler success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success fail:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
    
    IS_LEGAl(urlStr);
    
    AFHTTPSessionManager *manager = [NetworkServiceManager httpSessionManager];

    return [manager POST:urlStr parameters:parameter
            
                progress:^(NSProgress * _Nonnull uploadProgress) {
                    if (progressHandler) {
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            progressHandler(uploadProgress);
                        });
                    }
                }
                 success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                     if (success) {
                         success(task,responseObject);
                     }
                 }
                 failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     if (failure) {
                         failure(task,error);
                     }
                 }];
}

/**
 post请求
 
 @param urlStr 请求地址
 @param parameter 参数
 @param block 请求头构造block
 @param progressHandler 进度
 @param success 成功block
 @param failure 失败block
 @return task对象
 */
-(NSURLSessionDataTask *)executePostTask:(NSString *)urlStr parameters:(id)parameter constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block progress:(ProgressHandler)progressHandler success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success fail:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure {
    
    IS_LEGAl(urlStr);
    
    AFHTTPSessionManager *manager = [NetworkServiceManager httpUpLoadSessionManager];
    
    return [manager POST:urlStr parameters:parameter constructingBodyWithBlock:block
            
                progress:^(NSProgress * _Nonnull uploadProgress) {
                    if (progressHandler) {
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            progressHandler(uploadProgress);
                        });
                    }
                }
                 success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                     if (success) {
                         success(task,responseObject);
                     }
                 }
                 failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     if (failure) {
                         failure(task,error);
                     }
                 }];
}

@end
